package com.kaiwukj.android.ufamily.mvp.ui.page.mine.house.door;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.location.Location;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.app.constant.EventCode;
import com.kaiwukj.android.ufamily.di.component.DaggerMineComponent;
import com.kaiwukj.android.ufamily.di.module.MineModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.KaiwuEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DoorAccessDeviceResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DoorAccessRecordResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.MyHouseMemberResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.MyHouseResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.mine.MineContract;
import com.kaiwukj.android.ufamily.mvp.ui.page.mine.house.MyHousePresenter;
import com.kaiwukj.android.ufamily.mvp.ui.widget.CircleProgressBar;
import com.kaiwukj.android.ufamily.utils.location.CoordinateUtils;
import com.kaiwukj.android.ufamily.utils.location.LocationUtils;
import com.mob.tools.utils.LocationHelper;
import com.zghl.mclient.client.ZghlMClient;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterUrlKt.MineDoorAccessUrl)
public class DoorAccessActivity extends BaseMvpActivity<MyHousePresenter> implements MineContract.HouseView {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.line_progress)
    CircleProgressBar progressBar;
    @BindView(R.id.container_progress)
    ViewGroup containerProgress;
    @BindView(R.id.tv_community_location)
    TextView tvCommunityLocation;

    private int currentProgress = 0;
    private final int totalProgress = 100;
    private ValueAnimator addAnimator;
    private ValueAnimator delAnimator;

    private DoorListDialog doorListDialog;
    private DoorListDialog doorPassDialog;
    private List<DoorAccessDeviceResult.UnitListBean> doorDeviceResult;
    private List<DoorAccessDeviceResult.UnitListBean> passDeviceResult;


    @OnClick(R.id.container_left)
    void onBackClick() {
        onBackPressedSupport();
    }

    @OnClick(R.id.btn_pass_get)
    void onPassGet() {
        //showDeviceDialog(false);
        showPassDialog();
    }

    @OnClick({R.id.tv_door_record, R.id.tv_face_upload, R.id.tv_door_help})
    void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.tv_door_record:
                ARouter.getInstance().build(ARouterUrlKt.DoorRecordUrl).navigation();
                break;
            case R.id.tv_face_upload:
                ARouter.getInstance().build(ARouterUrlKt.FacePrewRouterUrl).navigation();
                break;
            case R.id.tv_door_help:
                showMessage("使用帮助");
                break;
        }
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        super.setupActivityComponent(appComponent);
        DaggerMineComponent.builder()
                .appComponent(appComponent)
                .mineModule(new MineModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_door_access;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView(Bundle savedInstanceState) {
        tvTitle.setVisibility(View.GONE);
        //progressBar.
        // simulateProgress();
        tvCommunityLocation.setText(getApp().getUserInfo().getLastCommunityName());
        containerProgress.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    simulateProgress();
                    if (delAnimator != null && delAnimator.isRunning()) {
                        delAnimator.cancel();
                    }
                    break;
                case MotionEvent.ACTION_CANCEL:
                    break;
                case MotionEvent.ACTION_UP:
                    if (addAnimator != null && addAnimator.isRunning()) {
                        addAnimator.cancel();
                    }
                    backProgress();
                    break;
            }
            return true;
        });

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mPresenter.fetchDevice();
        initLocation();

    }
/*
    private LocationService mLocationService;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mLocationService = ((LocationService.LocationBinder) service).getService();
            mLocationService.setOnGetLocationListener((lastLatitude, lastLongitude, latitude, longitude, country, locality, street) -> {
                runOnUiThread(() -> {
                    LogUtils.d("location------------------>" + latitude + "---" + longitude);
                });
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };*/


    public void initLocation() {
        LocationHelper helper = new LocationHelper();
        try {
            Location location = helper.getLocation(this);
            LogUtils.d("lllllll------------------>" + location.getLatitude() + "---" + location.getLongitude());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        //  bindService(new Intent(this, LocationService.class), conn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        //  unbindService(conn);
        super.onDestroy();
    }

    private void onProgressComplete() {
        showDeviceDialog(true);
    }

    private void onProgressCancel() {
    }

    private void simulateProgress() {
        addAnimator = ValueAnimator.ofInt(currentProgress, totalProgress);
        addAnimator.addUpdateListener(animation -> {
            currentProgress = (int) addAnimator.getAnimatedValue();
            progressBar.setProgress(currentProgress + 1);
            if (currentProgress + 1 == totalProgress) {
                addAnimator.cancel();
                onProgressComplete();
            }
        });
        addAnimator.setRepeatCount(ValueAnimator.INFINITE);
        addAnimator.setDuration(1000);
        addAnimator.start();
    }

    private void backProgress() {
        delAnimator = ValueAnimator.ofInt(0, currentProgress);
        int tempProgress = currentProgress;
        delAnimator.addUpdateListener(animation -> {
            currentProgress = tempProgress - (int) delAnimator.getAnimatedValue();
            progressBar.setProgress(currentProgress);
            if (currentProgress == 1) {
                delAnimator.cancel();
                onProgressCancel();
            }
        });
        delAnimator.setRepeatCount(ValueAnimator.INFINITE);
        delAnimator.setDuration(1000);
        delAnimator.start();
    }

    /**
     * @param isOpenDoor true:开门 false:获取密码
     */
    private void showDeviceDialog(boolean isOpenDoor) {
        if (doorListDialog == null) {
            doorListDialog = new DoorListDialog(this);
            doorListDialog.setOnCheckedListener(item -> {
                if (item == null) {
                    showMessage("请选择需要操作的大门");
                    return;
                }
                doorListDialog.cancel();
                LogUtils.d("isOpen------------------>" + isOpenDoor);
                if (doorListDialog.getType() == 1) {
                    if (isDoorInside(item.getGps())) {
                        showLoading("正在开门");
                        ZghlMClient.getInstance().openDoor(item.getDeviceId());
                    } else {
                        showMessage("不在安全范围内，请尝试打开手机定位或使用其他方式开门");
                    }
                } else {
                    ARouter.getInstance().build(ARouterUrlKt.DoorAccessPassUrl)
                            .withString("roomId", item.getZgORid())
                            .withString("roomName", item.getRoomName())
                            .navigation();
                }
            });
        }
        if (isOpenDoor) {
            if (doorDeviceResult != null && doorDeviceResult.size() > 0) {
                doorListDialog.setNewData(1, doorDeviceResult);
            } else {
                showMessage("没有找到门禁信息");
                return;
            }
        } else {
            if (passDeviceResult != null && passDeviceResult.size() > 0) {
                doorListDialog.setNewData(3, passDeviceResult);
            } else {
                showMessage("没有找到门禁信息");
                return;
            }
        }
        //doorListDialog.setType(isOpenDoor ? 1 : 3);
        doorListDialog.show();
    }

    /**
     *
     */
    private void showPassDialog() {
        if (doorPassDialog == null) {
            doorPassDialog = new DoorListDialog(this);
            doorPassDialog.setOnCheckedListener(item -> {
                if (item == null) {
                    showMessage("请选择需要操作的大门");
                    return;
                }
                doorPassDialog.cancel();
                if (doorPassDialog.getType() == 1) {
                    if (isDoorInside(item.getGps())) {
                        showLoading("正在开门");
                        ZghlMClient.getInstance().openDoor(item.getDeviceId());
                    } else {
                        showMessage("不在安全范围内，请尝试打开手机定位或使用其他方式开门");
                    }
                } else {
                    ARouter.getInstance().build(ARouterUrlKt.DoorAccessPassUrl)
                            .withString("roomId", item.getZgORid())
                            .withString("roomName", item.getRoomName())
                            .navigation();
                }
            });
        }
        if (passDeviceResult != null && passDeviceResult.size() > 0) {
            doorPassDialog.setNewData(3, passDeviceResult);
        } else {
            showMessage("没有找到门禁信息");
            return;
        }
        //doorListDialog.setType(isOpenDoor ? 1 : 3);
        doorPassDialog.show();
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onDoorOpenOkEvent(KaiwuEvent event) {
        if (event.getCode() == EventCode.EVENT_OPEN_DOOR) {
            hideLoading();
            showMessage("开门成功");
        }
    }

    //是否在安全范围内
    public boolean isDoorInside(String location) {
        boolean flag = false;
        if (StringUtils.isEmpty(location)) {
            return false;
        }
        try {
            String[] doorLocation = location.split(",");
            double doorLat = Double.parseDouble(doorLocation[1]);
            double doorLng = Double.parseDouble(doorLocation[0]);
            Location currLocationEncode = new LocationHelper().getLocation(this);
            double[] currLocation = CoordinateUtils.wgs84ToGcj02(currLocationEncode.getLongitude(), currLocationEncode.getLatitude());

            LogUtils.d("location----------------->" + currLocation[1] + "--" + currLocation[0]);
            double distance = LocationUtils.getDistance(doorLat, doorLng, currLocation[1], currLocation[0]);
            LogUtils.d("distance-------------------->" + distance);
            if (distance <= 200) {//安全范围200米
                flag = true;
            }
        } catch (Throwable e) {
            flag = false;
        }
        return flag;
    }

    @Override
    public void onFetchHouse(List<MyHouseResult> results) {

    }

    @Override
    public void onFetchHouseMember(List<MyHouseMemberResult> results) {
    }

    @Override
    public void onFetchDoorAccess(DoorAccessDeviceResult result) {
        hideLoading();
        doorDeviceResult = getDialogList(true, result);
        passDeviceResult = getDialogList(false, result);

    }

    public List<DoorAccessDeviceResult.UnitListBean> getDialogList(boolean isOpenDoor, DoorAccessDeviceResult result) {
        List<DoorAccessDeviceResult.UnitListBean> list = new ArrayList<>();
        if (isOpenDoor) {
            if (result.getCdList() != null && result.getCdList().size() > 0) {
                list.addAll(result.getCdList());
            }
            if (result.getUnitList() != null && result.getUnitList().size() > 0) {
                list.addAll(result.getUnitList());
            }
        } else {
            if (result.getRoomList() != null && result.getRoomList().size() > 0) {
                list.addAll(result.getRoomList());
            }
        }
        if (isOpenDoor) {
            Set<DoorAccessDeviceResult.UnitListBean> set =
                    new TreeSet<>((o1, o2) -> o1.getDeviceId().compareTo(o2.getDeviceId()));
            set.addAll(list);
            return new ArrayList<>(set);
        }
        Set<DoorAccessDeviceResult.UnitListBean> set2 =
                new TreeSet<>((o1, o2) -> o1.getZgORid().compareTo(o2.getZgORid()));
        set2.addAll(list);
        return new ArrayList<>(set2);
    }

    @Override
    public void onFetchDoorRecord(List<DoorAccessRecordResult> results) {

    }

    @Override
    public void onTaskErr(int taskId) {
        super.onTaskErr(taskId);
        hideLoading();
    }
}
